package com.example.rjxmgl.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.rjxmgl.entity.dos.Course;
import com.example.rjxmgl.entity.dos.StudentCourse;
import com.example.rjxmgl.form.CourseAndIsChoose;
import com.example.rjxmgl.mapper.CourseMapper;
import com.example.rjxmgl.service.CourseService;
import com.example.rjxmgl.utils.ResultMessage;
import com.example.rjxmgl.utils.ResultUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 课程表
 *
 * @author khai 951992121@qq.com
 * @since 1.0.0 2024-12-05
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {


    @Override
    public ResultMessage listCourse(Long studentId) {

        List<Course> list = Db.list(Course.class);
        ArrayList<CourseAndIsChoose> targetList = new ArrayList<>(list.size());
        for (Course course : list) {
            CourseAndIsChoose caic = new CourseAndIsChoose();
            caic.setCourse(course);
            StudentCourse one = Db.query(StudentCourse.class).eq("student_id", studentId)
                    .eq("course_id", course.getCourseId()).one();
            if(one==null){
                caic.setIsChoose(false);
            }else{
                caic.setIsChoose(true);
            }
            targetList.add(caic);
        }
        return ResultUtil.data(targetList);
    }

    @Override
    public ResultMessage chooseCourse(Long studentId, Long courseId) {

        StudentCourse one = Db.query(StudentCourse.class).eq("course_id", courseId).eq("student_id", studentId).one();
        if(one!=null){
            return ResultUtil.error(400,"已选课");
        }
        one=new StudentCourse();
        one.setCourseId(courseId);
        one.setStudentId(studentId);
        Db.save(one);
        return ResultUtil.success();

    }
    //
    @Override
    public ResultMessage noChooseCourse(Long studentId, Long courseId) {
        StudentCourse one = Db.query(StudentCourse.class).eq("course_id", courseId).eq("student_id", studentId).one();
        if(one==null){
            return ResultUtil.error(400,"未选课");
        }
        Db.removeById(one);
        return ResultUtil.success();
    }
}